package com.siyoumi.app.modules.iot.service;

import com.siyoumi.app.entity.IotDevice;
import com.siyoumi.app.entity.IotProduct;
import com.siyoumi.app.modules.iot.service.device_action.DeviceActionHandlePowerOn;
import com.siyoumi.app.modules.iot.service.device_action.DeviceActionHandleState;
import com.siyoumi.component.XRedis;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public abstract class DeviceActionHandle {
    public static String callbackKey(String id) {
        return "iot|callback:" + id;
    }

    IotProduct entity;

    public static DeviceActionHandle getInstance(IotProduct entityProduct) {
        DeviceActionHandle app = null;
        switch (entityProduct.getIpro_type()) {
            case "power_on":
                app = new DeviceActionHandlePowerOn();
                break;
            default:
                XValidator.err(EnumSys.ERR_VAL.getR("类型未开发，" + entityProduct.getIpro_type()));
        }
        app.setEntity(entityProduct);

        return app;
    }

    /**
     * 发送消息到设备
     *
     * @param entityDevice
     */
    abstract public XReturn send(IotDevice entityDevice);

    /**
     * 设备反馈，消息是否发送成功
     *
     * @param actionId
     */
    public XReturn callback(String actionId) {
        String redisKey = DeviceActionHandle.callbackKey(actionId);
        log.info("callback: {}", redisKey);
        String msg = XRedis.getBean().getAndDel(redisKey);
        if (XStr.isNullOrEmpty(msg)) {
            return XReturn.getR(20048, "action_id错误或消息已过期");
        }

        return XReturn.parse(msg);
    }


}
